<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Leaflet.draw</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
  </head>
  <body>
    <div id="map" style="height: 500px;"></div>
    <button id="drawCircle">绘制圆形</button>
    <button id="drawRectangle">绘制矩形</button>
    <button id="drawPolygon">绘制多边形</button>
    <button id="drawPolyline">绘制折线</button>

    <script>
      // 初始化地图
      const map = L.map('map').setView([39.92, 116.38], 13);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
      }).addTo(map);

      // 初始化 Leaflet.draw
      const drawnItems = new L.FeatureGroup();
      map.addLayer(drawnItems);
      const drawControl = new L.Control.Draw({
        edit: {
          featureGroup: drawnItems,
        },
        draw: {
          circle: false,
          rectangle: false,
          polygon: false,
          polyline: false,
        },
      });
      map.addControl(drawControl);

      // 定义绘制函数
      function draw(shapeType) {
        // 取消之前的绘制事件
        map.off('draw:created');

        // 启用新的绘制
        drawControl.setDrawingOptions({
          marker: false,
          circle: false,
          rectangle: false,
          polygon: false,
          polyline: false,
        });
        drawControl.setDrawingOptions({
          [shapeType]: true,
        });

        // 监听新的绘制事件
        map.once('draw:created', function (e) {
          const layer = e.layer;
          drawnItems.addLayer(layer);
        });
      }

      // 绑定按钮事件
      document.getElementById('drawCircle').addEventListener('click', function () {
        map.dragging.disable()
        draw('circle');
      });
      document.getElementById('drawRectangle').addEventListener('click', function () {
        draw('rectangle');
      });
      document.getElementById('drawPolygon').addEventListener('click', function () {
        draw('polygon');
      });
      document.getElementById('drawPolyline').addEventListener('click', function () {
        draw('polyline');
      });
    </script>
  </body>
</html>
